/*
 * Project: BooEditor
 * Author:  Johannes Kuhaupt
 * Last Change:
 *    by:   $Author: $
 *    date: $Date:   $
 * Copyright (c): Johannes Kuhaupt
 * Licence: Creative Commons CC BY-NC-SA 3.0
 */
package control;

import java.io.*;
import java.util.Enumeration;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author Johannes Kuhaupt
 */
public class SettingsManager {
    
    private static Properties tempSettings = new Properties();
    private static FileOutputStream propOutFile;

    
    
    
    
    
    
    /**
     * Checks if the config file is usable (readable, writeable, exists)
     * @return usability
     */
    public static boolean isConfigFileUsable(){
        try {
        File file = new File(System.getProperty("user.dir")+"/settings/leJosEditor.conf");
        if(file.exists()){
            if(file.canRead() && file.canWrite()){
                return true;
            }
            else{ return false;}
        }
        else{  return false;    }
      
      } catch (Exception ex) {
            Logger.getLogger(SettingsManager.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }
    
    
    /**
     * Checks if the config file is creatable
     * @return theCreatibility
     */
    public static boolean newConfigFileCreatable(){
        FileOutputStream propOutFile;
        boolean b = false;
        try {
            (new File("settings")).mkdir();
            propOutFile = new FileOutputStream(System.getProperty("user.dir")+"/settings/leJosEditor.conf");
            b= true;
        } catch (Exception ex) {
            Logger.getLogger(SettingsManager.class.getName()).log(Level.SEVERE, null, ex);
            b= false;
        }
        return b;
        
    }
    
    /**
     * Checks the config file (syntactical correctness)
     * @return
     */
    public static boolean hasRightConfigFileContent(){
        return true;
    }
    
    /**
     * Standard setting for first use (no config file created yet)
     * standard values for config file will be set
     */
    public static void createStandardSettings(){
        tempSettings.setProperty("LINENUMBERS", "true");
        tempSettings.setProperty("HIGHLIGHTACTIVELINE", "true");
        tempSettings.setProperty("SHOWSPACES", "false");
        tempSettings.setProperty("ANTIALIAS", "true");
        tempSettings.setProperty("FONTNAME", "Monospaced");
        tempSettings.setProperty("FONTSIZE", "13");
        tempSettings.setProperty("FONTSTYLE", "0");
        tempSettings.setProperty("FONTSIZEBIGSCREEN", "30");        
        tempSettings.setProperty("SYNTAXHIGHLIGHTING", "true");
        tempSettings.setProperty("HIGHLIGHTINGTHEME", "default");
        tempSettings.setProperty("AUTOINDENTATION", "true");
        tempSettings.setProperty("AUTOCOMPLETION", "false");        
        tempSettings.setProperty("INDENTATIONBYTAB", "true");
        tempSettings.setProperty("TABSIZE", "4");        
        tempSettings.setProperty("FRAMEWIDTH", "900");
        tempSettings.setProperty("FRAMEHEIGHT", "600");
        tempSettings.setProperty("FRAMEPOSITIONX", "0");
        tempSettings.setProperty("FRAMEPOSITIONY", "0");
        
    }
    
    

    
    
    /**
     * Create a new config file, so that the settings can be stored / saved.
     */
    public static void makeConfigFile() {
        Writer pw = null;
        try {
            (new File("settings")).mkdir();
            pw = new FileWriter( System.getProperty("user.dir")+"/settings/leJosEditor.conf" );
            
            tempSettings.store( propOutFile, "" );
            
            
        } catch (Exception ex) {
            Logger.getLogger(SettingsManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally{
            try { pw.close(); } catch ( Exception e ) { }
        }
    }

   

    
    
    /**
     * Config file is read. Checks also if two instances of BooEditor are
     * running.
     */
    public static void readConfig() {
        FileReader reader=null;
        try {
            reader = new FileReader(System.getProperty("user.dir")+"/settings/leJosEditor.conf");
            tempSettings.load(reader);
            
        } catch (Exception ex) {
            JFrame start = new JFrame("Start");
            JOptionPane.showMessageDialog(start,"Fehler beim Einlesen der Config-Datei. Läuft das Programm bereits?", "Start-Fehler",
    JOptionPane.ERROR_MESSAGE);
            start.dispose();
            System.exit(1);           
            Logger.getLogger(SettingsManager.class.getName()).log(Level.SEVERE, null, ex);
            System.err.println("Error, readConfig failed: "+ ex.toString());
            
        }
        finally{
            try { reader.close(); } catch ( Exception e ) { }
        }
        
    }
    
    /**
     * Debug method. Prints all setting to screen.
     */
    public static void printSettings(){
        Enumeration e = tempSettings.propertyNames();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            System.out.println(key + " -- " + tempSettings.getProperty(key));
        }        
                
    }
    
    /**
     * Write the user settings in the config file.
     */
    public static void writeSettingsToFile(){
        
        try {
            propOutFile = new FileOutputStream(System.getProperty("user.dir")+"/settings/leJosEditor.conf");
            
                tempSettings.store( propOutFile, "" );
            
        } catch (Exception ex) {
            Logger.getLogger(SettingsManager.class.getName()).log(Level.SEVERE, null, ex);
            System.err.println("Error,  writeSetttingsToFile failed: " + ex.toString());
        }
                    
    }
         
        
    
    
    /**
     *
     * @param pKey
     * @return
     */
    public static String getStringSettingValue(String pKey){
        return tempSettings.getProperty(pKey);
        
    }
    
    /**
     *
     * @param pKey
     * @return theValue as String
     */
    public static boolean getBooleanSettingValue(String pKey){
        if(tempSettings.getProperty(pKey).equals("true")) return true;
        else{
            if(tempSettings.getProperty(pKey).equals("false")){ return false;}
            else {throw new IllegalArgumentException();}
        }       
        
    }
    
    /**
     *
     * @param pKey
     * @return theValue as int
     */
    public static int getIntSettingValue(String pKey){
        return Integer.parseInt(tempSettings.getProperty(pKey));
    }
    
    /**
     *
     */
    public static void checkProperties(){
        //vorhanden
        //schreibar
        //korrekt
    }
    
    /**
     * Update option item
     * @param pItem
     * @param pValue
     */
    public static void updateSettingsItem(String pItem, String pValue){
            tempSettings.setProperty(pItem, pValue);
    }
    
    
    
    
}
